package admin

import (
	"context"
	"fmt"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/module/admin/adminLogic"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/utils/database"
	"grpc.getaway.adminspro.padmins.com/pkg/config/businessError"
	pbAdmin "grpc.getaway.adminspro.padmins.com/pkg/proto/admin"
)

func (rpc *admin) AdminOperationLogDetail(ctx context.Context, pb *pbAdmin.AdminOperationLogDetailReq) (*pbAdmin.AdminOperationLogDetailResp, error) {
	where := "id=?"
	bindValue := []interface{}{pb.Id}
	if pb.OperaterId != 0 {
		adminIds := adminLogic.GetChildrenRoleAdminIds(ctx, pb.OperaterId, true)
		where += " and admin_id in (?)"
		bindValue = append(bindValue, adminIds)
	}

	Db := database.Db.GetDefaultDb(ctx)

	row, dbErr := Db.Find(fmt.Sprintf("select * from admin_operation_log where %s", where), bindValue...)
	if dbErr != nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
	}

	if row == nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.NotFound)
	}

	return &pbAdmin.AdminOperationLogDetailResp{
		Row: &pbAdmin.AdminOperationLog{
			Id:         row["id"].(int64),
			AdminId:    row["admin_id"].(int64),
			Username:   row["username"].(string),
			Url:        row["url"].(string),
			Title:      row["title"].(string),
			Content:    row["content"].(string),
			Ip:         row["ip"].(string),
			Useragent:  row["useragent"].(string),
			CreateTime: row["create_time"].(string),
		},
	}, nil
}
